package cn.edu.scau.cmi.aop.service;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.edu.scau.cmi.ema.domain.Address;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.domain.Foodtype;
import cn.edu.scau.cmi.yanghongyu.dao.FrontEchartDAO;
import cn.edu.scau.cmi.yanghongyu.util.FoodtypeLibraryUtil;

@Aspect
@Component
public class EventAspectJ {

	@Autowired
	FrontEchartDAO frontEchartDAO;

//	@AfterReturning(value="execution(* cn.edu.scau.cmi.ema.service.EventService.saveEvent(..))", returning="event")
	public void updateEchart(JoinPoint jp, Event event) {
//		Event e = (Event) jp.getArgs()[0];
		Integer eventId = event.getId();
		String eventName = event.getName();
		Foodtype foodtype = event.getFoodbatch().getFood().getFoodtype();
		String foodtypeName = foodtype.getName();
//		获取食物类型的根类型
		Integer rootFoodtypeId = FoodtypeLibraryUtil.getFoodtypeLibrary(foodtype.getId());


		String sourceCountry = null;
		String sourceProvince = null;
		String sourceCity = null;
		String discoveryCountry = null;
		String discoveryProvince = null;
		String discoveryCity = null;
		Address address = event.getSourceAddress();
		while (address != null && address.getLevel() > 1) {
			if (address.getLevel() == 4)
				sourceCity = address.getName();
			else if (address.getLevel() == 3)
				sourceProvince = address.getName();
			else if (address.getLevel() == 2)
				sourceCountry = address.getName();
			address = address.getParent();
		}
		address = event.getDiscoveryAddress();
		while (address != null && address.getLevel() > 1) {
			if (address.getLevel() == 4)
				discoveryCity = address.getName();
			else if (address.getLevel() == 3)
				discoveryProvince = address.getName();
			else if (address.getLevel() == 2)
				discoveryCountry = address.getName();
			address = address.getParent();
		}

		frontEchartDAO.updateOrSave2echartBySql(eventId, eventName, sourceCountry, sourceProvince, sourceCity,
				discoveryCountry, discoveryProvince, discoveryCity, foodtypeName, rootFoodtypeId);
	}

	
	/**
	 * web端的删除和批量删除都是调用EventService.deleteEvent()的，所以只需要使用这个切片——杨宏宇
	 * @param jp
	 */
//	@AfterReturning(value="execution(* cn.edu.scau.cmi.ema.service.EventService.deleteEvent(..))")
	public void deleteEchart(JoinPoint jp) {
		// 获取事件id
		Event e = (Event) jp.getArgs()[0];
		Integer eventId = e.getId();
		// 根据set中的id删除echart中的记录
		frontEchartDAO.deleteEchartsBySql(eventId);
	}
	
//	@AfterReturning(value="execution(* cn.edu.scau.cmi.ema.service.EventService.deleteEvents(..))")
//	public void deleteEcharts(JoinPoint jp) {
//		Set<Integer> set = (Set<Integer>) jp.getArgs()[0];
//		// 根据set中的id删除echart中的记录
//		yanghongyuDAO.deleteEchartsByIds(set);
//	}
	
}